package com.guqj.nio.netty.serialization.protobuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class SubscribeServerHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {

	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
		System.out.println("Service accept client subscribe req: [" + req + "]");
		ctx.writeAndFlush(doResp(req.getSubReqID()));
	}

	private SubscribeResProto.SubscribeRes doResp(int subReqId) {
		SubscribeResProto.SubscribeRes.Builder builder = SubscribeResProto.SubscribeRes.newBuilder();
		builder.setSubReqID(subReqId);
		builder.setRespCode(0);
		builder.setDesc("订购成功，欢迎下次再来！");
		return builder.build();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

}
